package com.ywl.designpattern.singleton.type2;

/**
 * @author yuwl
 * @description 单例设计模式-饿汉式（静态代码块，可用-线程安全-可能造成内存浪费）
 * @since 2024-02-29 09:18
 */
public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    static {
        singleton = new Singleton();
    }

    public static Singleton getInstance() {
        return singleton;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + ", instance = " + instance);
                System.out.println(Thread.currentThread().getName() + ", instance.hashCode() = " + instance.hashCode());
            }).start();
        }
    }
}
